import 'package:city_pickers/city_pickers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:short_drama/utils/colors.dart';

import '../../models/bank_card_info_model.dart';
import '../../utils/http_util.dart';
import '../../utils/validate.dart';
import 'package:short_drama/utils/float.dart';

class BindPage extends StatefulWidget {
  const BindPage({super.key});

  @override
  State<BindPage> createState() => _BindPageState();
}

class _BindPageState extends State<BindPage> {
  bool isEdit = false;
  String address = '';
  final TextEditingController _namecontroller = TextEditingController();
  final TextEditingController _banknumbercontroller = TextEditingController();
  final TextEditingController _banknamecontroller = TextEditingController();
  final TextEditingController _bankcontroller = TextEditingController();
  final TextEditingController _phonecontroller = TextEditingController();
  final TextEditingController _codecontroller = TextEditingController();

  @override
  void initState() {
    super.initState();
    queryInfo();
  }

  Future<void> queryInfo() async {
    EasyLoading.show(status: 'loading', maskType: EasyLoadingMaskType.clear);
    try {
      final result = await HttpUtil().get('member/cashout_account/firstinfo');
      final dynamic responseData = result.data['data']; // 明确类型声明
      if (responseData != null) {
        isEdit = true;
        BankCardInfoModel value = BankCardInfoModel.fromJson(responseData);
        _namecontroller.text = value.realname ?? '';
        _banknumbercontroller.text = value.account_no ?? '';
        _banknamecontroller.text = value.bank_name ?? '';
      }
    } catch (e) {
      EasyLoading.showToast('请求失败');
    }
    EasyLoading.dismiss();
  }

  Future<void> addInfo(
    String name,
    String cardNo,
    String bankName,
    String subBank,
    String address,
  ) async {
    EasyLoading.show(status: 'loading', maskType: EasyLoadingMaskType.clear);
    try {
      final result = await HttpUtil().post(
        'member/cashout_account',
        params: {
          "bank_name": bankName,
          "account_type": "bank",
          "realname": name,
          "account_no": cardNo,
          "bank_city": subBank,
        },
      );
      final dynamic responseData = result.data['data']; // 明确类型声明
      EasyLoading.showToast('添加成功');
      Get.back();
    } catch (e) {
      EasyLoading.showToast('请求失败');
    }
    EasyLoading.dismiss();
  }

  Future<void> modifyInfo(
    String name,
    String cardNo,
    String bankName,
    String subBank,
    String address,
  ) async {
    EasyLoading.show(status: 'loading', maskType: EasyLoadingMaskType.clear);
    try {
      final result = await HttpUtil().put(
        'member/cashout_account/2',
        params: {
          "bank_name": bankName,
          "account_type": "bank",
          "realname": name,
          "account_no": cardNo,
          "bank_city": subBank,
        },
      );
      final dynamic responseData = result.data['data']; // 明确类型声明
      EasyLoading.showToast('修改成功');
      Get.back();
    } catch (e) {
      EasyLoading.showToast('请求失败');
    }
    EasyLoading.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ClientColors.ff0a0f12,
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.white),
        leading: IconButton(
          onPressed: () => {Get.back()},
          icon: Icon(Icons.arrow_back_ios),
        ),
        centerTitle: false,
        titleSpacing: FloatConstance.navBarSpace,
        actions: [
          GestureDetector(
            onTap: () {
              _doneAction();
            },
            child: Container(
              margin: EdgeInsets.only(right: 10),
              child: Text(
                '完成',
                style: TextStyle(fontSize: 14, color: ClientColors.ff4abc9c),
              ),
            ),
          ),
        ],
        backgroundColor: ClientColors.odffffff,
        title: Text(
          '银行卡绑定',
          style: TextStyle(color: Colors.white, fontSize: 18),
        ),
      ),
      body: GestureDetector(
        onTap: () {
          onTap();
        },
        child: Container(
          margin: EdgeInsets.only(top: 32),
          child: Column(
            spacing: 10,
            children: [
              // 账户名称
              _createTextField(context, 0, '账户名称', _namecontroller),
              _createTextField(context, 0, '银行卡号', _banknumbercontroller),
              _createTextField(context, 0, '银行名称', _banknamecontroller),
              _createTextField(context, 0, '开户行', _bankcontroller),
              _createChooseText(context, 0, '所在地'),
              // _createTextField(context, 0, '手机号', _phonecontroller),
              // _createTextField(context, 0, '请输入验证码', _codecontroller),
            ],
          ),
        ),
      ),
    );
  }

  Widget _createTextField(
    BuildContext context,
    int index,
    String title,
    TextEditingController controller,
  ) {
    return Container(
      margin: EdgeInsets.only(left: 16, right: 16),
      padding: EdgeInsets.only(left: 16, right: 16),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        color: ClientColors.odffffff,
      ),
      height: 60,
      child: Row(
        children: [
          Text(
            title,
            style: TextStyle(fontSize: 15, color: ClientColors.aaffffff),
          ),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 10),
              child: TextField(
                autofocus: true,
                keyboardType: TextInputType.name,
                decoration: InputDecoration(border: InputBorder.none),
                textAlign: TextAlign.right,
                style: TextStyle(color: Colors.white),
                controller: controller,
                onSubmitted: (value) => onTap(),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _createChooseText(BuildContext context, int index, String title) {
    return Container(
      margin: EdgeInsets.only(left: 16, right: 16),
      padding: EdgeInsets.only(left: 16, right: 16),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
        color: ClientColors.odffffff,
      ),
      height: 60,
      child: Row(
        children: [
          Text(
            title,
            style: TextStyle(fontSize: 15, color: ClientColors.aaffffff),
          ),
          Expanded(
            child: GestureDetector(
              onTap: () {
                //choose address
                getResult().then((Result? result) {
                  if (result != null) {
                    setState(() {
                      address =
                          '${result.provinceName ?? ''}${result.cityName ?? ''}${result.areaName ?? ''}';
                    });
                  }
                });
              },
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 10),
                child: Row(
                  children: [
                    Expanded(
                      child: Text(
                        address,
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    Image.asset(
                      'assets/images/icon_user_arrow.png',
                      width: 6,
                      height: 12,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Future<Result?> getResult() async {
    Result? result = await CityPickers.showCityPicker(context: context);
    return result;
  }

  onTap() async {
    FocusScope.of(context).unfocus();
  }

  _doneAction() async {
    final name = _namecontroller.text;
    final banknumber = _banknumbercontroller.text;
    final bankname = _banknamecontroller.text;
    final bank = _bankcontroller.text;
    // final phone = _phonecontroller.text;
    // final code = _codecontroller.text;
    if (name.isEmpty) {
      EasyLoading.showToast('请输入账户名称');
      return;
    }
    if (banknumber.isEmpty) {
      EasyLoading.showToast('请输入银行卡号');
      return;
    }
    if (bankname.isEmpty) {
      EasyLoading.showToast('请输入银行名称');
      return;
    }
    if (bank.isEmpty) {
      EasyLoading.showToast('请输入开户行');
      return;
    }
    if (address.isEmpty) {
      EasyLoading.showToast('请输入所在地');
      return;
    }
    if (isEdit) {
      modifyInfo(name, banknumber, bankname, bank, address);
    } else {
      addInfo(name, banknumber, bankname, bank, address);
    }
  }
}
